package cn.gx.kevin.common.utils;

import java.net.InetAddress;

/**
 * 从org.hibernate.id.UUIDHexGenerator.java中搬来
 * 与java.util.UUID生成的uuid的不同：本类生成id有序，java.util.UUID无序 <b>uuid</b><br>
 *
 * A <tt>UUIDGenerator</tt> that returns a string of length 32, This string will
 * consist of only hex digits. Optionally, the string may be generated with
 * separators between each component of the UUID.
 *
 * Mapping parameters supported: separator.
 */
public class UUIDHexGenerator {

	private static final String IPHexString;
	private static short counter = (short) 0;
	private static final String JVMHexString;

	static {
		int ip;
		try {
			ip = toInt(InetAddress.getLocalHost().getAddress());
		} catch (Exception e) {
			ip = 0;
		}
		IPHexString = format(ip);
		int JVM = (int) (System.currentTimeMillis() >>> 8);
		JVMHexString = format(JVM);
	}

	protected static int toInt(byte[] bytes) {
		int result = 0;
		for (int i = 0; i < 4; i++) {
			result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
		}
		return result;
	}

	public static String generate() {
		return format(getHiTime()) + IPHexString + JVMHexString + format(getLoTime()) + format(getCount());
	}

	protected static short getCount() {
		synchronized (UUIDHexGenerator.class) {
			if (counter < 0) {
				counter = 0;
			}				
			return counter++;
		}
	}

	protected static short getHiTime() {
		return (short) (System.currentTimeMillis() >>> 32);
	}

	protected static int getLoTime() {
		return (int) System.currentTimeMillis();
	}

	protected static String format(int intValue) {
		String formatted = Integer.toHexString(intValue);
		StringBuilder buf = new StringBuilder("00000000");
		buf.replace(8 - formatted.length(), 8, formatted);
		return buf.toString();
	}

	protected static String format(short shortValue) {
		String formatted = Integer.toHexString(shortValue);
		StringBuilder buf = new StringBuilder("0000");
		buf.replace(4 - formatted.length(), 4, formatted);
		return buf.toString();
	}

	public static void main(String[] args) {
		int i = 0;
		while (i < 50) {
			System.out.println(UUIDHexGenerator.generate());
			i++;
		}
	}

}